package com.advert.presentation.tools;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import java.io.Serializable;
import java.util.LinkedList;

@Name("userActivity")
@Scope(ScopeType.SESSION)
public class UserActivityManager implements Serializable {
    private final int HISTORY_SIZE = 5;

    @In("facesHelper")
    private FacesHelper facesHelper;

    private LinkedList<String> visitedUrls;


    public String getLastUrl() {
        String retVal = null;
        if (!visitedUrls.isEmpty()) {
            retVal = visitedUrls.getFirst();    
        }
        return retVal;
    }

    public String previousUrl(int stepsBeforeCurrent) {
        String retVal = null;
        if (stepsBeforeCurrent > 0 && stepsBeforeCurrent < HISTORY_SIZE) {
            if (visitedUrls.size() > stepsBeforeCurrent) {
                retVal = visitedUrls.get(stepsBeforeCurrent);
            }
        }
        return retVal;
    }


    @Observer("org.jboss.seam.beforePhase")
    public synchronized void urlVisited(PhaseEvent event) {
        if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
            String url = facesHelper.getServletRequest().getRequestURL() + "?" + facesHelper.getServletRequest().getQueryString();
            if (!url.equals(getLastUrl())) {
                visitedUrls.addFirst(url);
                trimList();
            }
        }
    }

    @Create
    public void init() {
        visitedUrls = new LinkedList<String>();
    }

    private void trimList() {
        while(visitedUrls.size() > HISTORY_SIZE) {
            visitedUrls.removeLast();
        }
    }
}
